<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="展览标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入展览标题" />
      </el-form-item>
      <el-form-item label="参与院校" prop="joinSchool">
        <el-select
          v-model="formData.joinSchool"
          placeholder="请选择参与院校"
          multiple
          clearable
          :loading="formLoading"
          filterable
        >
          <el-option
            v-for="item in joinSchoolList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合作单位" prop="cooperationUnit">
        <el-select
          v-model="formData.cooperationUnit"
          placeholder="请选择合作单位"
          multiple
          clearable
          :loading="formLoading"
          filterable
        >
          <el-option
            v-for="item in cooperationUnitList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="封面" prop="cover">
        <UploadImg v-model="formData.cover" />
      </el-form-item>
      <el-form-item label="展览类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择展览类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.Exhibition_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="展会介绍" prop="description">
        <Editor v-model="formData.description" height="300px" />
      </el-form-item>
      <el-form-item label="是否删除" prop="deleted">
        <el-select v-model="formData.deleted" placeholder="请选择是否删除">
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布者" prop="userId">
        <el-input v-model="formData.userId" placeholder="请输入发布者" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          type="date"
          value-format="x"
          placeholder="选择开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formData.endTime"
          type="date"
          value-format="x"
          placeholder="选择结束时间"
        />
      </el-form-item>
      <el-form-item label="作者寄语" prop="authorsMessage">
        <el-input v-model="formData.authorsMessage" placeholder="请输入作者寄语" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { ExhibitionApi, ExhibitionVO } from '@/api/td/exhibition'

/** 展览 表单 */
defineOptions({ name: 'ExhibitionForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: undefined,
  joinSchool: undefined,
  cooperationUnit: undefined,
  cover: undefined,
  type: undefined,
  description: undefined,
  deleted: undefined,
  userId: undefined,
  startTime: undefined,
  endTime: undefined,
  authorsMessage: undefined,
})
const formRules = reactive({
  title: [{ required: true, message: '展览标题不能为空', trigger: 'blur' }],
  joinSchool: [{ required: true, message: '参与院校不能为空', trigger: 'blur' }],
  cooperationUnit: [{ required: true, message: '合作单位不能为空', trigger: 'blur' }],
  cover: [{ required: true, message: '封面不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '展览类型不能为空', trigger: 'change' }],
  description: [{ required: true, message: '展会介绍不能为空', trigger: 'blur' }],
  deleted: [{ required: true, message: '是否删除不能为空', trigger: 'change' }],
  userId: [{ required: true, message: '发布者不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取下拉框数据
  await getSelectData()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ExhibitionApi.getExhibition(id)
      // 转换字符串为数组
      if (typeof data.joinSchool === 'string') {
        data.joinSchool = data.joinSchool.split(',').filter(Boolean)
      }
      if (typeof data.cooperationUnit === 'string') {
        data.cooperationUnit = data.cooperationUnit.split(',').filter(Boolean)
      }
      formData.value = data
      console.log('设置表单数据：', formData.value) // 添加日志便于调试
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value }
    // 转换数组为字符串
    if (Array.isArray(data.joinSchool)) {
      data.joinSchool = data.joinSchool.join(',')
    }
    if (Array.isArray(data.cooperationUnit)) {
      data.cooperationUnit = data.cooperationUnit.join(',')
    }
    if (formType.value === 'create') {
      await ExhibitionApi.createExhibition(data)
      message.success(t('common.createSuccess'))
    } else {
      await ExhibitionApi.updateExhibition(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    joinSchool: undefined,
    cooperationUnit: undefined,
    cover: undefined,
    type: undefined,
    description: undefined,
    deleted: undefined,
    userId: undefined,
    startTime: undefined,
    endTime: undefined,
    authorsMessage: undefined,
  }
  formRef.value?.resetFields()
}

/** 下拉框数据 */
const joinSchoolList = ref([])
const cooperationUnitList = ref([])

/** 获取下拉框数据 */
const getSelectData = async () => {
  try {
    // 获取院校数据
    const schoolRes = await ExhibitionApi.getJoinSchoolList()
    
    if (!schoolRes) {
      message.warning('获取院校数据失败：服务器未返回数据')
      return
    }
    
    // 检查返回的数据是否是数组
    if (Array.isArray(schoolRes)) {
      joinSchoolList.value = schoolRes
      console.log('设置院校数据成功：', joinSchoolList.value)
    } else {
      console.error('院校数据格式错误:', schoolRes) 
      message.warning('获取院校数据失败：数据格式不正确')
      return
    }
    
    // // 获取合作单位数据
    // const unitRes = await ExhibitionApi.getCooperationUnitList()
    // if (Array.isArray(unitRes)) {
    //   cooperationUnitList.value = unitRes
    //   console.log('设置合作单位数据成功：', cooperationUnitList.value)
    // } else {
    //   message.warning('获取合作单位数据失败')
    // }
  } catch (error) {
    console.error('获取下拉框数据失败:', {
      error,
      message: error.message,
      stack: error.stack
    })
    message.error(`获取下拉框数据失败: ${error.message || '服务器异常'}`)
  }
}
</script>
